package com.spark.lola.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spark.lola.entity.SupplierToken;
import com.spark.lola.logistics.entity.Message;
import com.spark.lola.logistics.service.MessageService;
import com.spark.lola.support.api.entity.EnterpriseTokenUser;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.common.QueryCondition;
import com.spark.lola.support.mybatis.entity.QueryParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * @author: Zhi-peng wang
 * @date: 2020/06/19 11:32
 **/
@RestController
@RequestMapping(value = "/api/message", produces = "application/json;charset=utf-8")
@Api(value = "/api/message", tags = "消息中心")
public class MessageController {

    @Autowired
    private MessageService messageService;

    @ApiOperation(value = "分页查询消息")
    @RequestMapping(value = "/findBy", method = RequestMethod.POST)
    public ResponseBean findBy(@RequestBody QueryParam<Message> queryBean, @SessionAttribute SupplierToken tokenUser) {
        queryBean.setQueryList(new ArrayList<>());
        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setKey("o.userId");
        queryCondition.setOper("=");
        queryCondition.setValue(tokenUser.getSupplierId());
        queryBean.getQueryList().add(queryCondition);
        return ResponseBean.success(messageService.findPage(queryBean));
    }

    @ApiOperation(value = "设置已读")
    @RequestMapping(value = "/read/{id}", method = RequestMethod.POST)
    public ResponseBean read(@PathVariable String id, @SessionAttribute SupplierToken tokenUser) {
        messageService.updateUsedByIds(CommonConstant.Y, id);
        return ResponseBean.success();
    }

    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public ResponseBean delete(@PathVariable String id, @SessionAttribute SupplierToken tokenUser) {
        messageService.removeById(id);
        return ResponseBean.success();
    }

    @ApiOperation(value = "清空")
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public ResponseBean clear(@SessionAttribute EnterpriseTokenUser<?> tokenUser) {
        QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", tokenUser.getShiroUser().getId());
        messageService.remove(queryWrapper);
        return ResponseBean.success();
    }

}
